package com.hxd.otc.module.my.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.BaseActivity;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.login.activity.PhoneCodeActivity;
import com.hxd.otc.module.my.bean.ImageCodeBean;
import com.hxd.otc.module.my.contract.ChangePhoneContract;
import com.hxd.otc.module.my.presenter.ChangePhonePresenter;
import com.hxd.otc.utils.UIUtils;
import com.hxd.otc.widget.EditInfoInputView;
import com.hxd.otc.widget.TitleBar;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * Created by lzy on 2018/6/15 0015.
 * description ${修改绑定手机号}
 */
public class ChangePhoneActivity extends BaseActivity<ChangePhonePresenter> implements ChangePhoneContract.View {
    @BindView(R.id.title_bar)
    TitleBar mTitleBar;
    @BindView(R.id.et_old_phone)
    EditText mEtOldPhone;
    @BindView(R.id.editInfoInputView_ver_code)
    EditInfoInputView mEditInfoInputViewVerCode;
    @BindView(R.id.btn_verification_code)
    TextView mBtnVerificationCode;
    @BindView(R.id.et_new_phone)
    EditText mEtNewPhone;
    @BindView(R.id.editInfoInputView_new_ver_code)
    EditInfoInputView mEditInfoInputViewNewVerCode;
    @BindView(R.id.btn_new_verification_code)
    TextView mBtnNewVerificationCode;
    @BindView(R.id.tv_new_phone_label)
    TextView mTvNewPhoneLabel;
    @BindView(R.id.ll_new_phone)
    LinearLayout llNewPhone;
    @BindView(R.id.tv_old_phone_label)
    TextView mTvOldPhoneLabel;
    @BindView(R.id.tv_area_code)
    TextView mTvAreaCode;
    @BindView(R.id.tv_old_area_code)
    TextView tvOldAreaCode;

    private Disposable mDisposable1;
    private Disposable mDisposable2;
    private String mPhoneCode = Constant.Login.DEFAULT_PHONE_CODE;
    private String mOldPhoneCode = Constant.Login.DEFAULT_PHONE_CODE;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_change_phone;
    }

    @Override
    protected ChangePhonePresenter createPresenter() {
        return new ChangePhonePresenter(this);
    }

    @Override
    protected void initView() {
        boolean isBoundPhone = UserHelper.isBoundPhone();

        if (isBoundPhone) {
            mEtOldPhone.setEnabled(false);
            mEtOldPhone.setText(UserHelper.getMobile());
        }

        mTvOldPhoneLabel.setText(isBoundPhone ? R.string.old_phone_numbers : R.string.phone_numbers);
        mTitleBar.setTitleText(getString(isBoundPhone ? R.string.modify_bind_phone_number : R.string.bind_phone_number));
        mTvNewPhoneLabel.setVisibility(isBoundPhone ? View.VISIBLE : View.GONE);
        llNewPhone.setVisibility(isBoundPhone ? View.VISIBLE : View.GONE);
        mEtNewPhone.setVisibility(isBoundPhone ? View.VISIBLE : View.GONE);
        tvOldAreaCode.setVisibility(isBoundPhone ? View.GONE : View.VISIBLE);
        mBtnNewVerificationCode.setVisibility(isBoundPhone ? View.VISIBLE : View.GONE);
        mEditInfoInputViewNewVerCode.setVisibility(isBoundPhone ? View.VISIBLE : View.GONE);
    }

    @OnClick({R.id.btn_verification_code, R.id.btn_new_verification_code, R.id.tv_confirm, R.id.tv_area_code, R.id.tv_old_area_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_verification_code:
                onGetVerCode();//获取手机验证码
                break;
            case R.id.btn_new_verification_code:
                onGetNewVerCode();//获取新手机验证码
                break;
            case R.id.tv_confirm:
                onConfirm();//确认
                break;
            case R.id.tv_area_code:
                $startActivityForResult(PhoneCodeActivity.class, Constant.Login.LOGIN_TO_PHONE_CODE_REQUEST_CODE);
                break;
            case R.id.tv_old_area_code:
                $startActivityForResult(PhoneCodeActivity.class, 123);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.Login.LOGIN_TO_PHONE_CODE_REQUEST_CODE:
                    mPhoneCode = data.getStringExtra(Constant.Login.PHONE_CODE_DATA);
                    mTvAreaCode.setText("+" + mPhoneCode);
                    break;
                case 123:
                    mOldPhoneCode = data.getStringExtra(Constant.Login.PHONE_CODE_DATA);
                    tvOldAreaCode.setText("+" + mOldPhoneCode);
                    break;
            }
        }
    }

    /**
     * 获取验证码：用户绑定时获取验证码和重新绑定获取旧手机号验证码
     */
    private void onGetVerCode() {

        String phone = mEtOldPhone.getText().toString().trim();

        if (!UIUtils.isMobile(phone)) {
            showToast(mEtOldPhone.getHint().toString());
            return;
        }

        if (UserHelper.isBoundPhone()) {//修改绑定
            mPresenter.getUpdatePhoneVerCode(phone, "", true);
        } else {//进行绑定
            mPresenter.findUser(phone);
        }
    }

    /**
     * 绑定手机号时的获取新验证码
     */
    private void onGetNewVerCode() {
        String phone = mEtNewPhone.getText().toString().trim();
        if (!UIUtils.isMobile(phone)) {
            return;
        }
        mPresenter.findUser(phone);
    }

    @Override
    public void checkNewPhoneSuccess(String phone, ImageCodeBean imageCodeBean) {
        if (UserHelper.isBoundPhone()) {
            mPresenter.getUpdatePhoneVerCode(phone, mPhoneCode, false);//新绑定
        } else {
            mPresenter.getNewBoundPhoneVerCode(phone);//未绑定时使用
        }
    }

    private void startCountdown1() {
        ViewGroup.LayoutParams layoutParams = mBtnVerificationCode.getLayoutParams();
        layoutParams.width = mBtnVerificationCode.getWidth();
        mBtnVerificationCode.setLayoutParams(layoutParams);
        mBtnVerificationCode.setEnabled(false);
        if (mDisposable1 != null && !mDisposable1.isDisposed()) {
            mDisposable1.dispose();
            mDisposable1 = null;
        }
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mDisposable1 = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBtnVerificationCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        mBtnVerificationCode.setEnabled(true);
                        mBtnVerificationCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();

    }


    @Override
    public void getUpdatePhoneVerCodeSuccess(String msg, boolean isOld) {
        if (isOld) {
            startCountdown1();
        } else {
            startCountdown2();
        }
    }

    @Override
    public void checkNewPhoneFail(String errMessage) {
        showToast(errMessage);
    }

    @Override
    public void getUpdatePhoneVerCodeFail(String errMessage, boolean isOld) {
        showToast(errMessage);
        if (isOld) {
            mBtnNewVerificationCode.setEnabled(true);
        } else {
            mBtnNewVerificationCode.setEnabled(true);
        }
    }

    @Override
    public void getNewPhoneVerCodeSuccess(String msg) {
        startCountdown1();
    }

    @Override
    public void getNewPhoneVerCodeFail(String errMessage) {
        showToast(errMessage);
        mBtnNewVerificationCode.setEnabled(true);
    }

    @Override
    public void conBindPhoneSuccess(String phone, String msg) {
        UserHelper.updateMobile(phone);
        showToast(msg);
        finish();
    }

    @Override
    public void onModifyBoundPhoneSuccess(String newPhone, String msg) {
        UserHelper.updateMobile(newPhone);
        showToast(msg);
        finish();
    }

    private void startCountdown2() {
        ViewGroup.LayoutParams layoutParams = mBtnNewVerificationCode.getLayoutParams();
        layoutParams.width = mBtnNewVerificationCode.getWidth();
        mBtnNewVerificationCode.setLayoutParams(layoutParams);
        mBtnNewVerificationCode.setEnabled(false);
        if (mDisposable2 != null && !mDisposable2.isDisposed()) {
            mDisposable2.dispose();
            mDisposable2 = null;
        }
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mDisposable2 = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBtnNewVerificationCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        //倒计时完毕置为可点击状态
                        mBtnNewVerificationCode.setEnabled(true);
                        mBtnNewVerificationCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();

    }

    private void onConfirm() {
        if (UserHelper.isBoundPhone()) {//修改绑定
            onModifyBoundPhone();
        } else {//新绑定
            onNewBoundPhone();
        }
    }

    /**
     * 未绑定，新绑定
     */
    private void onNewBoundPhone() {
        String phone = mEtOldPhone.getText().toString().trim();
        if (!UIUtils.isMobile(phone)) {
            return;
        }
        String verCode = mEditInfoInputViewVerCode.getText();
        if (TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.phone_code_not_null));
            return;
        }
        mPresenter.onBindPhone(phone, verCode, mOldPhoneCode);
    }

    /**
     * 修改绑定手机号
     */
    private void onModifyBoundPhone() {

        String verCode = mEditInfoInputViewVerCode.getText();
        if (TextUtils.isEmpty(verCode)) {
            showToast(getString(R.string.phone_code_not_null));
            return;
        }

        String newPhone = mEtNewPhone.getText().toString().trim();
        if (!UIUtils.isMobile(newPhone)) {
            return;
        }

        String newVerCode = mEditInfoInputViewNewVerCode.getText();
        if (TextUtils.isEmpty(newVerCode)) {
            showToast(getString(R.string.new_phone_code_not_null));
            return;
        }

        mPresenter.onModifyBoundPhone(newPhone, verCode, newVerCode, mPhoneCode);
    }


    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected void onDestroy() {
        if (mDisposable1 != null && !mDisposable1.isDisposed()) {
            mDisposable1.dispose();
            mDisposable1 = null;
        }

        if (mDisposable2 != null && !mDisposable2.isDisposed()) {
            mDisposable2.dispose();
            mDisposable2 = null;
        }
        super.onDestroy();
    }
}
